//
//  DpViewController.m
//  南京大牌档
//
//  Created by student on 13-12-25.
//  Copyright (c) 2013年 无锡第三团队. All rights reserved.
//

#import "DpViewController.h"
#import "MainViewController.h"
#import "DpCell.h"
@interface DpViewController ()

@end

@implementation DpViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.hidesBottomBarWhenPushed=YES;
        self.tabBarController.tabBar.hidden=YES;
         self.navigationItem.titleView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"nagation.png"]];
    }
    return self;
}


- (void)viewDidLoad
{
    [super viewDidLoad];    
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0)
    {
        self.edgesForExtendedLayout = UIRectEdgeNone;
        self.extendedLayoutIncludesOpaqueBars = NO;
        self.modalPresentationCapturesStatusBarAppearance = NO;
    }
#endif

    dpArray=[[NSMutableArray alloc]init];
    [self requsetData];
}
-(void)requsetData
{
    NSArray *urlArray=[NSArray arrayWithObjects:@"1942651",@"15106050",@"6323471",@"5315981",@"538176",@"538685",@"15104588",@"15969237",@"7992674",@"4174680",@"9027742",@"5409921",@"6025818",nil];
 
    NSArray *cityArray=[NSArray arrayWithObjects:@"%E5%8D%97%E4%BA%AC",@"%E5%8C%97%E4%BA%AC",nil];
    
    NSError *error;
    for (int i=0; i<8; i++) {
  
        NSString *urlString=[NSString stringWithFormat:@"http://api.dianping.com/v1/deal/get_deals_by_business_id?appkey=192082892&sign=85863FDA441391D4EBCDA71F91EB651BD25ADD7B&business_id=%@&city=%@",urlArray[i],cityArray[0]];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
    NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error];
        if ([[dic objectForKey:@"status"]isEqualToString:@"OK"]) {
            [dpArray addObject:dic];
        }
    }
    
  
    for (int j=8; j<13; j++) {
        NSString *urlString=[NSString stringWithFormat:@"http://api.dianping.com/v1/deal/get_deals_by_business_id?appkey=192082892&sign=85863FDA441391D4EBCDA71F91EB651BD25ADD7B&business_id=%@&city=%@",urlArray[j],cityArray[1]];
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
        NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error];
        if ([[dic objectForKey:@"status"]isEqualToString:@"OK"]) {
            [dpArray addObject:dic];
        }
    }
    
    dpScrollView=[[UIScrollView alloc]initWithFrame:CGRectMake(0,0,320,WXHLApplicationBounds().size.height)];
    dpScrollView.delegate=self;
    dpScrollView.backgroundColor=[UIColor whiteColor];
    dpScrollView.contentSize=CGSizeMake(320*dpArray.count, WXHLApplicationBounds().size.height);
    dpScrollView.showsVerticalScrollIndicator=NO;
    dpScrollView.showsHorizontalScrollIndicator=NO;
    dpScrollView.pagingEnabled=YES;
    dpScrollView.bounces=NO;
   
    
    dpPageControl = [[UIPageControl alloc]initWithFrame:CGRectMake(85,365,150,10)];
    dpPageControl.numberOfPages =dpArray.count;
    dpPageControl.layer.cornerRadius=5;
    dpPageControl.alpha=0.5;
    dpPageControl.currentPage = 0;
    dpPageControl.backgroundColor =[UIColor blackColor];
    
    /*
     {"status":"OK",
     "count":1,
     "deals":[{"deal_id":"5-5221757",
               "title":"南京大牌档现金券",
               "description":"仅售75元,价值100元现金抵用券!新店开张,喜迎新年,大牌档新店同贺马年,马上有优惠!",
               "city":"南京",
               "list_price":100.0,
               "current_price":75.0,
               "regions":["草场门/龙江"],
               "categories":["本帮江浙菜"],
               "purchase_count":255,
               "purchase_deadline":"2014-03-15",
               "publish_date":"2014-01-16",
               "details":"团购详情\n - 现金抵用券（1张，价值100元）\n- 现金抵用券（1张，价值1.1元） \n",
               "image_url":"http://t1.s2.dpfile.com/pc/mc/320a88e68873f1f8f598166dce246e09(450x280)/thumb.jpg",
               "s_image_url":"http://t2.s2.dpfile.com/pc/mc/320a88e68873f1f8f598166dce246e09(160x100)/thumb.jpg",
               "more_image_urls":["http://t2.s2.dpfile.com/pc/mc/320a88e68873f1f8f598166dce246e09(450x1024)/thumb.jpg","http://t2.s1.dpfile.com/pc/mc/f991bf6fc3bedda10f01746b0250ed44(450x1024)/thumb.jpg"],
                "more_s_image_urls":["http://t2.s2.dpfile.com/pc/mc/320a88e68873f1f8f598166dce246e09(450x1024)/thumb_1.jpg","http://t2.s1.dpfile.com/pc/mc/f991bf6fc3bedda10f01746b0250ed44(450x1024)/thumb_1.jpg"],
                "is_popular":1,
                "restrictions":{"is_reservation_required":0,
                                "is_refundable":0,
                                "special_tips":"购买须知\n \n有效期 \n2014-01-16 至 2014-03-15\n除外日期：大年三十至正月初五、2月14日\n \n预约 \n无需预约\n \n使用须知 \n不可抵扣范围：海鲜、酒水、特价菜\n \n温馨提示 \n仅限大厅使用，商家不提供包间\n100元现金券仅限人民广场世茂店使用\n到店仅限大厅堂食，不提供餐前打包；餐后未吃完，可打包（打包费以店内实际为准）\n本单谢绝自带酒水饮料\n不兑现、不可找零\n团购券请于到店时出示\n如需团购券发票，请在消费时向商户提出\n不可与其他优惠同享\n本单团购不支持退款\n本单团购不支持使用大众点评抵用券\n \n \n"
                                },
                "notice":"",
                "deal_url":"http://dpurl.cn/p/a1-J6wnRmf",
                "deal_h5_url":"http://dpurl.cn/p/P4ARiS-me5",
                "commission_ratio":0.03,
                "businesses":[{"name":"南京大牌档(龙江店)","id":538685,"city":"南京","address":"草场门大街96号中青大厦1楼","latitude":32.058807,"longitude":118.74251,"url":"http://dpurl.cn/p/HJEbJEaD0y","h5_url":"http://dpurl.cn/p/7j7nUOh8Hh"}]
      }]
     }
     */
    for (int i=0; i<dpArray.count; i++) {
        UIImageView *dpImage=[[UIImageView alloc]initWithFrame:CGRectMake(i*320,0, 320, 140)];
        [dpImage setImageWithURL:[NSURL URLWithString:[[dpArray[i]objectForKey:@"deals"][0]objectForKey:@"image_url"]]];
        [dpScrollView addSubview:dpImage];
        
        UILabel *titleLabel=[[UILabel alloc]initWithFrame:CGRectMake(i*320, 145, 320, 20)];
        titleLabel.text=[[dpArray[i]objectForKey:@"deals"][0]objectForKey:@"title"];
        titleLabel.font=[UIFont systemFontOfSize:20];
        titleLabel.backgroundColor=[UIColor clearColor];
        [dpScrollView addSubview:titleLabel];
        
        UILabel *descriptionLabel=[[UILabel alloc]initWithFrame:CGRectMake(i*320, 165, 320, 30)];
        descriptionLabel.text=[[dpArray[i]objectForKey:@"deals"][0]objectForKey:@"description"];
        descriptionLabel.font=[UIFont systemFontOfSize:10];
        descriptionLabel.numberOfLines=3;
        descriptionLabel.backgroundColor=[UIColor clearColor];
        [dpScrollView addSubview:descriptionLabel];
        
        UILabel *special_tipsLabel=[[UILabel alloc]initWithFrame:CGRectMake(i*320, 195, 320, 180)];
        special_tipsLabel.text=[[[dpArray[i]objectForKey:@"deals"][0]objectForKey:@"restrictions"]objectForKey:@"special_tips"];
        special_tipsLabel.font=[UIFont systemFontOfSize:6];
        special_tipsLabel.numberOfLines=30;
        special_tipsLabel.backgroundColor=[UIColor clearColor];
        [dpScrollView addSubview:special_tipsLabel];
        
        UILabel *nameLabel=[[UILabel alloc]initWithFrame:CGRectMake(i*320,375, 320, 10)];
        nameLabel.text=[NSString stringWithFormat:@"支持门店：%@ 地址：%@",[[[dpArray[i]objectForKey:@"deals"][0]objectForKey:@"businesses"][0]objectForKey:@"name"],[[[dpArray[i]objectForKey:@"deals"][0]objectForKey:@"businesses"][0]objectForKey:@"address"]];
        nameLabel.font=[UIFont systemFontOfSize:10];
        nameLabel.numberOfLines=1;
        nameLabel.backgroundColor=[UIColor clearColor];
        [dpScrollView addSubview:nameLabel];
        
        UIButton *buyButton=[[UIButton alloc]initWithFrame:CGRectMake(i*320+50, 395, 220, 20)];
        [buyButton setTitle:@"立即购买" forState:UIControlStateNormal];
        buyButton.layer.cornerRadius=5;
        buyButton.tag=i;
        buyButton.backgroundColor=[UIColor redColor];
        [dpScrollView addSubview:buyButton];
        [buyButton addTarget:self action:@selector(buyButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    }
    [self.view addSubview:dpScrollView];
    [self.view addSubview:dpPageControl];
    
    
}

-(void)buyButtonPressed:(UIButton *)button
{
    
    NSString *keyString=[[dpArray[button.tag]objectForKey:@"deals"][0]objectForKey:@"deal_id"];
    NSArray *array=[keyString componentsSeparatedByString:@"-"];
    NSURL *url = [NSURL URLWithString: [NSString stringWithFormat:@"dianping://tuandeal?id=%@",array[1]]];
    if([[UIApplication sharedApplication] canOpenURL:url]) {
        [[UIApplication sharedApplication] openURL:url];
    } else {
        //没有安装应用，默认打开HTML5站
        NSString *keywords = [@"南京大牌档(龙江店)" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        url = [NSURL URLWithString:[NSString stringWithFormat:@"http://m.dianping.com/search.aspx?skey=%@",keywords]];

        [[UIApplication sharedApplication] openURL:url];
    }

}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    dpPageControl.currentPage =scrollView.contentOffset.x/320;
    
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
